﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DBControl;
using System.Data;
using System.Data.SqlClient;

namespace ProjectX
{
    public partial class Search : Errorbase
    {
        private string cateid = "";
        private string catelevel = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["cate"] == null || Request.QueryString["lvl"] == null)
            {
                Response.Redirect("/404.htm",false);
            }
            else
            {
                cateid = Request.QueryString["cate"];
                catelevel = Request.QueryString["lvl"];

                if (cateid == "-1" || catelevel == "-1")
                {
                    cateid = catelevel = "-1";
                }

                if (!IsPostBack)
                {
                    if (Session["userNick"] != null)
                    {
                        this.username.Text = Session["userNick"].ToString();
                        this.loginlink.Visible = false;
                        this.reglink.Visible = false;
                        this.logout.Visible = true;
                    }
                    try
                    {
                        GetCateName(cateid, catelevel);
                        GetCateTree(cateid, catelevel);
                        bindview(cateid);
                        if (this.baobeiView.Rows.Count != 0)
                        {
                            getTotalCount(cateid);
                            this.AspNetPager.Visible = true;
                        }
                    }
                    catch (Exception)
                    {
                        Response.Redirect("/404.htm", false);
                    }
                }
            }
        }

        private void GetCateName(string cid,string cidlevel)
        {
            SystemLib slb = new SystemLib();
            int newlevel = int.Parse(cidlevel) + 1;
            SqlDbHelper sdh = new SqlDbHelper();
            string strsql = "SELECT * FROM CidCount WHERE Cid='"+ cid +"' AND [Count] > 0";
            System.Data.DataTable dt = sdh.ExecuteDataTable(strsql);
            HyperLink hl = new HyperLink();
            hl.Text = "所有类目";
            hl.NavigateUrl = "AllCate.html";
            this.CateTitle.Controls.Add(hl);

            if (dt.Rows.Count > 0)
            {
                if (cidlevel.Equals("1"))
                {
                    Label lb = new Label();
                    Label lbf = new Label();
                    lbf.CssClass = "spanfen";
                    lbf.Text = ">";
                    lb.Text = dt.Rows[0]["name"].ToString();
                    this.CateTitle.Controls.Add(lbf);
                    this.CateTitle.Controls.Add(lb);
                    this.Title = "淘我想淘 · " + lb.Text;
                }
                else
                {
                    string tmp_cidtree = dt.Rows[0]["Cidtree"].ToString().TrimEnd(',');
                    foreach (var item in tmp_cidtree.Split(','))
                    {
                        string itemstr = "SELECT * FROM CidCount WHERE Cid='" + item + "' AND [Count] > 0";
                        System.Data.DataTable newdt = sdh.ExecuteDataTable(itemstr);

                        if (newdt.Rows[0]["Cidlevel"].ToString().Equals(cidlevel))
                        {
                            Label lb = new Label();
                            Label lbf = new Label();
                            lbf.CssClass = "spanfen";
                            lbf.Text = ">";
                            lb.Text = newdt.Rows[0]["name"].ToString();
                            this.CateTitle.Controls.Add(lbf);
                            this.CateTitle.Controls.Add(lb);
                            this.Title = "淘我想淘 · " + lb.Text;
                            break;
                        }
                        else
                        {
                            HyperLink hl2 = new HyperLink();
                            Label lbf = new Label();
                            lbf.CssClass = "spanfen";
                            lbf.Text = ">";
                            hl2.Text = newdt.Rows[0]["name"].ToString();
                            //hl2.NavigateUrl = "Search.aspx?cate=" + slb.Base64Encoding(newdt.Rows[0]["Cid"].ToString()) + "&lvl=" + slb.Base64Encoding(newdt.Rows[0]["Cidlevel"].ToString());
                            hl2.NavigateUrl = "Search/" + newdt.Rows[0]["Cid"].ToString() + "/" + newdt.Rows[0]["Cidlevel"].ToString() + ".html";
                            this.CateTitle.Controls.Add(lbf);
                            this.CateTitle.Controls.Add(hl2);
                        }
                    }
                }
            }
        }

        private void GetCateTree(string cid,string lel)
        {
            int lvl = int.Parse(lel) + 1;

            SqlDbHelper sdh = new SqlDbHelper();
            string strsql = "SELECT * FROM CidCount WHERE  Cidlevel = " + lvl + " AND CHARINDEX('," + cid + ",',','+cidtree+',') > 0 AND [Count] > 0";
            
            System.Data.DataTable dt = sdh.ExecuteDataTable(strsql);
            this.CateList.DataSource = dt;
            this.CateList.DataBind();

            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    list.Add("<li><a href=\"Search.aspx?cate=" + dt.Rows[i]["Cid"].ToString() + "&lvl=" + dt.Rows[i]["Cidlevel"].ToString() + "\" target=\"_self\"\">" + dt.Rows[i]["Name"].ToString().Trim() + "(" + dt.Rows[i]["count"] + ")" + "</a></li>");
            //}
        }

        protected void CateList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataRowView drv = e.Item.DataItem as DataRowView;
                SystemLib slb = new SystemLib();
                string cid = drv.Row["Cid"].ToString();
                string level = drv.Row["Cidlevel"].ToString();
                //string cateid = slb.Base64Encoding(cid);
                //string catelevel = slb.Base64Encoding(level);
                HyperLink hl = e.Item.FindControl("catelink") as HyperLink;
                hl.NavigateUrl = "Search/" + cid + "/" + level + ".html";
            }
            else if (e.Item.ItemType == ListItemType.Footer)
            {
                if (this.CateList.Items.Count == 0)
                {
                    this.CateList.ShowFooter = true;
                }
            }
            
            //this.CateList.ShowFooter = true;
        }

        private void bindview(string cid)
        {
            SqlDbHelper sdh = new SqlDbHelper();
            string sqlwhere = " WHERE cateid IN (select cid from cidcount where charindex('," + cid + ",',','+cidtree+',') > 0) AND [Status] = 0";
            //string getlist = "SELECT * FROM BuyersinfoR WHERE cateid IN (select cid from cidcount where charindex('" + cid + "',cidtree) > 0)";

            //this.baobeiView.DataSource = sdh.ExecuteDataTable(getlist);

            SqlParameter p1 = new SqlParameter("@tablename", "BuyersinfoR");//视图名或表名
            SqlParameter p2 = new SqlParameter("@pagerow", this.AspNetPager.PageSize);         //每页显示记录数 
            SqlParameter p3 = new SqlParameter("@pagenow", this.AspNetPager.CurrentPageIndex); //当前显示第几页 
            SqlParameter p4 = new SqlParameter("@ordercol", "Starttime");//排序字段
            SqlParameter p5 = new SqlParameter("@order", 1);//排序顺序，0升序，1降序
            SqlParameter p6 = new SqlParameter("@where", sqlwhere);


            SqlParameter[] paras = new SqlParameter[] { p1, p2, p3, p4, p5, p6 };
            
            //int count = int.Parse(sdh.ExecuteScalar("SELECT COUNT(*) FROM BuyersinfoR" + where).ToString());
            this.baobeiView.DataSource = sdh.ExecuteDataTable("sp_page", System.Data.CommandType.StoredProcedure, null, paras);
            this.baobeiView.DataBind();
        }

        private void getTotalCount(string cid)
        {
            SqlDbHelper sdh = new SqlDbHelper();
            string sqlcount = "SELECT COUNT(*) FROM BuyersinfoR WHERE cateid IN (select cid from cidcount where charindex('," + cid + ",',','+cidtree+',') > 0)";
            this.AspNetPager.RecordCount =  int.Parse(sdh.ExecuteScalar(sqlcount).ToString());
        }

        protected void AspNetPager_PageChanged(object sender, EventArgs e)
        {
            bindview(cateid);
            ScriptManager.RegisterStartupScript(AspNetPager, this.GetType(), "resizeimg", "<script>ResizeImg();</script>", false);
        }
        protected void logout_Click(object sender, EventArgs e)
        {
            Session.Clear();
            Response.Write("<script language='javascript'>window.parent.location.href='/'</script>");
        }
    }
}